package com.meida.module.system.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.meida.common.constants.QueueConstants;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.DeleteModel;
import com.meida.common.mybatis.model.PageModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaDelete;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.system.client.entity.SysCollecon;
import com.meida.module.system.client.entity.SysCompany;
import com.meida.module.system.client.enums.ColleconEnum;
import com.meida.module.system.provider.mapper.SysColleconMapper;
import com.meida.module.system.provider.service.SysColleconService;
import com.meida.module.system.provider.service.SysGroupColleconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 收藏点赞关注表 服务实现类
 *
 * @author flyme
 * @date 2019-06-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysColleconServiceImpl extends BaseServiceImpl<SysColleconMapper, SysCollecon> implements SysColleconService {

    @Autowired
    private SysGroupColleconService groupColleconService;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public SysCollecon findCollecon(Long targetId, Long userId, ColleconEnum colleconEnum, String entityName) {
        CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
        cq.eq("targetId", targetId);
        cq.eq("optType", colleconEnum.getCode());
        cq.eq("targetEntity", entityName);
        cq.eq(true, "userId", userId);
        return getOne(cq);
    }

    @Override
    public ResultBody collecon(Long targetId, ColleconEnum colleconEnum, String entityName, Long[] groupIds) {
        Long userId = OpenHelper.getUserId();
        SysCollecon sysCollecon = findCollecon(targetId, userId, colleconEnum, entityName);
        if (ObjectUtils.isEmpty(sysCollecon)) {
            sysCollecon = new SysCollecon();
            sysCollecon.setOptType(colleconEnum.getCode());
            sysCollecon.setTargetId(targetId);
            sysCollecon.setUserId(userId);
            sysCollecon.setTargetEntity(entityName);
            save(sysCollecon);
            if (FlymeUtils.isNotEmpty(groupIds)) {
                setGroup(new Long[]{sysCollecon.getColleconId()}, groupIds);
            }
            //发布收藏点击事件
            amqpTemplate.convertAndSend(QueueConstants.QUEUE_COLLECON, sysCollecon);
            return ResultBody.ok(colleconEnum.getName() + "成功", true);
        } else {
            removeById(sysCollecon.getColleconId());
            groupColleconService.deleteByColleconIds(new Long[]{sysCollecon.getColleconId()});
            return ResultBody.ok("已取消" + colleconEnum.getName(), false);
        }
    }

    @Override
    public Boolean setGroup(Long[] colleconIds, Long[] groupIds) {
        //先清空分组
        groupColleconService.deleteByColleconIds(colleconIds);
        //重新设置分组
        return groupColleconService.setColleconGroup(colleconIds, groupIds);
    }

    @Override
    public Integer countCollecon(Long targetId, ColleconEnum colleconEnum, Class cls) {
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.allNotNull(userId, targetId)) {
            CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
            cq.eq(true, "targetId", targetId);
            cq.eq("optType", colleconEnum.getCode());
            cq.eq("targetEntity", cls.getSimpleName());
            cq.eq(true, "userId", userId);
            return count(cq);
        } else {
            return 0;
        }
    }

    @Override
    public Integer countAllCollecon(Long targetId, ColleconEnum colleconEnum, Class cls) {
        if (FlymeUtils.isNotEmpty(targetId)) {
            CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
            cq.eq("targetId", targetId);
            cq.eq("optType", colleconEnum.getCode());
            cq.eq("targetEntity", cls.getSimpleName());
            return count(cq);
        } else {
            return 0;
        }

    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<EntityMap> selectColleconProductByCompanyId(Long companyId, int limit) {
        EntityMap map = new EntityMap();
        map.put("companyId", companyId);
        map.put("limit", limit);
        return baseMapper.selectColleconProductByCompanyId(map);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody pageList(PageModel model) {
        CriteriaQuery cq = new CriteriaQuery(model, SysCollecon.class);
        Long userId = OpenHelper.getUserId();
        cq.select("collecon.colleconId", "collecon.targetId", "collecon.targetEntity", "collecon.userId");
        cq.eq("collecon.userId", userId);
        return basePageList(cq);
    }

    @Override
    public ResultBody delete(DeleteModel model) {
        CriteriaDelete cd = new CriteriaDelete(model, SysCollecon.class);
        Long[] ids = model.getIds();
        groupColleconService.deleteByColleconIds(ids);
        return baseDelete(cd);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Integer countCountByTargetCompany(Long targetCompanyId, ColleconEnum colleconEnum, Class cls) {
        CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
        cq.eq(true, "targetCompanyId", targetCompanyId);
        cq.eq("optType", colleconEnum.getCode());
        cq.eq("targetEntity", cls.getSimpleName());
        return count(cq);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Integer countCountByUser(Long userId, ColleconEnum colleconEnum, Class cls) {
        CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
        cq.eq("optType", colleconEnum.getCode());
        cq.eq("targetEntity", cls.getSimpleName());
        cq.eq(true, "userId", userId);
        return count(cq);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody totalByTargetEntity() {
        EntityMap result = new EntityMap();
        CriteriaQuery cq = new CriteriaQuery(SysCollecon.class);
        String begin = DateUtils.minusDays(30).toString();
        cq.select("count(colleconId) total");
        cq.select(SysCompany.class, "companyName name");
        cq.eq("optType", 1);
        cq.eq("targetEntity", "SysCompany");
        cq.createJoin(SysCompany.class).setMainField("targetId");
        cq.groupBy("targetId");
        cq.orderByDesc("count(colleconId)");
        cq.limit(7);
        List<EntityMap> list = selectEntityMap(cq);
        return ResultBody.ok(list);
    }
}
